//do something config the frame
//所谓的frame 只是保存些配置信息。
//依赖 jquery.ui.notice.js,jquery.ui.dialog.js
//
/**
 * frame。js包含了frame必须的基础功能。frame.js会分别嵌入到jquery和window上。
 * 调用通过f$.*。当然通过Jquery或$可以拿到frame对象进而也可以
 * frame.js的功能包含：
 * 缓冲字典数据，并作解析。
 * 拦截delete请求，做confirm。
 * 所有操作返回message对象都可以被统一提示。
 * 工具方法集：
 * 清除表单数据的方法 clearForm  clearFields clearInputs resetForm
 * 将json对象转化为json字符串  $.toJSON 
 * 将form序列化为一个json对象 $.fn.serializeJson
 * 
 */
(function( $, w,undefined ) {
	
	var Frame=function(element, options){
		   
	    }, 
	    escape = /["\\\x00-\x1f\x7f-\x9f]/g,
		meta = {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"' : '\\"',
			'\\': '\\\\'
		},
	    hasOwn = Object.prototype.hasOwnProperty,
	    notice=$("body").notice();
	
	//jquery的静态函数
	   $.quoteString=function (str) {
			if (str.match(escape)) {
				return '"' + str.replace(escape, function (a) {
					var c = meta[a];
					if (typeof c === 'string') {
						return c;
					}
					c = a.charCodeAt();
					return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
				}) + '"';
			}
			return '"' + str + '"';
		},
	   $.toJSON=function(o){//将json对象转化为json字符串
		   if (o === null) {
				return 'null';
			}

			var pairs, k, name, val,type = $.type(o);

			if (type === 'undefined') {
				return undefined;
			}

			// Also covers instantiated Number and Boolean objects,
			// which are typeof 'object' but thanks to $.type, we
			// catch them here. I don't know whether it is right
			// or wrong that instantiated primitives are not
			// exported to JSON as an {"object":..}.
			// We choose this path because that's what the browsers did.
			if (type === 'number' || type === 'boolean') {
				return String(o);
			}
			if (type === 'string') {
				return $.quoteString(o);
			}
			if (typeof o.toJSON === 'function') {
				return $.toJSON(o.toJSON());
			}
			if (type === 'date') {
				var month = o.getUTCMonth() + 1,
					day = o.getUTCDate(),
					year = o.getUTCFullYear(),
					hours = o.getUTCHours(),
					minutes = o.getUTCMinutes(),
					seconds = o.getUTCSeconds(),
					milli = o.getUTCMilliseconds();

				if (month < 10) {
					month = '0' + month;
				}
				if (day < 10) {
					day = '0' + day;
				}
				if (hours < 10) {
					hours = '0' + hours;
				}
				if (minutes < 10) {
					minutes = '0' + minutes;
				}
				if (seconds < 10) {
					seconds = '0' + seconds;
				}
				if (milli < 100) {
					milli = '0' + milli;
				}
				if (milli < 10) {
					milli = '0' + milli;
				}
				return '"' + year + '-' + month + '-' + day + 'T' +
					hours + ':' + minutes + ':' + seconds +
					'.' + milli + 'Z"';
			}

			pairs = [];

			if ($.isArray(o)) {
				for (k = 0; k < o.length; k=k+1) {
					pairs.push($.toJSON(o[k]) || 'null');
				}
				return '[' + pairs.join(',') + ']';
			}

			// Any other object (plain object, RegExp, ..)
			// Need to do typeof instead of $.type, because we also
			// want to catch non-plain objects.
			if (typeof o === 'object') {
				for (k in o) {
					// Only include own properties,
					// Filter out inherited prototypes
					if (hasOwn.call(o, k)) {
						// Keys must be numerical or string. Skip others
						type = typeof k;
						if (type === 'number') {
							name = '"' + k + '"';
						} else if (type === 'string') {
							name = $.quoteString(k);
						} else {
							continue;
						}
						type = typeof o[k];

						// Invalid values like these return undefined
						// from toJSON, however those object members
						// shouldn't be included in the JSON string at all.
						if (type !== 'function' && type !== 'undefined') {
							val = $.toJSON(o[k]);
							pairs.push(name + ':' + val);
						}
					}
				}
				return '{' + pairs.join(',') + '}';
			}
	   };
	    
	//frame相关   
	Frame.prototype = {
	   constructor: Frame,
	   notice:function(message,rp){//系统提醒框
		   notice.setMessage(message,rp).show(1800).hide(2300);
	   },
	   /**
		 * frame前端的字典信息处理过程。如果字典信息不存在则更新。否则直接使用现有字典信息进行解析。
		 * @param type  字典分类
		 * @param code 字典值
		 */
	   getCodeInfo:function(type,code){
			
			var codes=$("body").data("codes"),curCode;
			
			if(!codes){
				//如果body中没有获取到数据则说明是第一次加载，加载并整理缓冲数据  
				$.ajax({
					url:"mgr/refreshCache.do",
					type:"POST",
					global:false,//避免触发全局事件，提高效率
					async:false,//只有当前处理完成后，后续操作才可以继续
					dataType:'json',
					success:function(data){
					    codes={};
						for ( var i = 0,len=data.length; i < len; i=i+1) {
							if(codes[data[i].dtid]){
								codes[data[i].dtid].push(data[i]);
							}else{
								Object.defineProperty(codes, data[i].dtid, {value:[data[i]],writable:true,enumerable:true});
							}
						}
						//缓冲数据重新放入body中
						$("body").data("codes",codes);
						console.log("缓冲数据更新完成！");
					}
				});
			}
			
			try{
				curCode=codes[type];//获取当前字典类型下的字典信息
				for ( var i = 0,len=curCode.length; i < len; i=i+1) {
					if(code==curCode[i].did){
						return curCode[i].dname;
					}
				}
			}catch(e){
				return "<span color='red'>无法找到对应的字典信息</span>";
			}
			
	   },
		//以下是日期函数,js处理日期对象的函数
	};
	
	w.f$=new Frame();//添加为window属性
	//以下为jquery 扩展
	$.fn.frame=function(){
		return new Frame();
	};
	$.fn.frame.defaults = {};
	$.fn.frame.Constructor = Frame;
	
	// copy from the form.js
	$.fn.clearForm = function() {
	    return this.each(function() {
	        $('input,select,textarea', this).clearFields();
	    });
	};
	/**
	 * Clears the selected form elements.
	 *  copy from the form.js
	 */
	$.fn.clearFields = $.fn.clearInputs = function() {
	    return this.each(function() {
	        var t = this.type, tag = this.tagName.toLowerCase();
	        if (t == 'text' || t == 'password' || tag == 'textarea')
	            this.value = '';
	        else if (t == 'checkbox' || t == 'radio')
	            this.checked = false;
	        else if (tag == 'select')
	            this.selectedIndex = -1;
	    });
	};
	/**
	 * Resets the form data.  Causes all form elements to be reset to their original value.
	 * copy from the form.js
	 */
	$.fn.resetForm = function() {
	    return this.each(function() {
	        // guard against an input with the name of 'reset'
	        // note that IE reports the reset function as an 'object'
	        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
	            this.reset();
	    });
	};
	
	//将form序列化为一个json对象
	$.fn.serializeJson=function(){
		var serializeObj={},
		    array=this.serializeArray();
//		    str=this.serialize();
		$(array).each(function(){
			if(serializeObj[this.name]){
				if($.isArray(serializeObj[this.name])){
				   serializeObj[this.name].push(this.value);
				}else{
				   serializeObj[this.name]=[serializeObj[this.name],this.value];
				}
			}else{
			    serializeObj[this.name]=this.value;
			}
		});
		return serializeObj;
	};
	
	
	//配置全局异步请求的提示消息
	(function(){
		
		//针对删除操作做的统一的提示方法。相当于拦截器。
		//删除请求必须是请求路径中包含 delPattern 中所列关键字的请求
		$('body').append('<div id="frame-confirm" style="display: none;" title="确认框">您确认删除吗？</div>');
		$.ajaxSetup({
			abortable:true//该请求是否可以被取消
		});
		$(document).ajaxSend(function(xhr,request,settings){
			var delPattern=/del|Del|DEL|delete|Delete|DELETE/;
			 if(delPattern.test(settings.url)){
				 //如果请求中包含删除字样，则先abort掉当前请求，并弹出确认框
				 if(settings.abortable){
						settings.abortable=false;
						request.abort();
						$("#frame-confirm").dialog({
						    autoOpen: true,
						    modal: true,
						  //隐藏默认的关闭按钮
						    open: function (event, ui) {
						       $(".ui-dialog-titlebar-close", $(this).parent()).hide();
						    },
						    closeOnEscape: false,
						    resizable: false,
						    draggable: false,
						    buttons: {
								"取消": function () {
						            $(this).dialog("close");
						        },
						        "确定": function () {
						            $(this).dialog("close");
						            $.ajax(settings.url,settings);
						        }
						    }
						});
				 }
				
			 }
			 
		 });//删除请求提示拦截结束
		
		//全局的消息提示，请求到后台返回的消息内容在这里进行处理提示
		$(document).ajaxSuccess(function(a,b,c,feedback){
			if(feedback.msg){//如果可以获取到消息（代码）则说明这是个消息
				$("body").notice(feedback).show(1800).hide(2300);
			}
	    });
		//请求发生异常时的处理逻辑
		$(document).ajaxError(function(event,request, settings,thrownError){
			if(request.status===401){//请求被拒绝，权限不够
				f$.notice("FSE0008",[settings.url]);
			}
	    });
		
		
	})();
}( jQuery,window ) );
